const Student = require('../controllers/studentController')
const Manager = require('../controllers/managerController')
const SigninRecord = require('../controllers/signinrecordController')
const Prize = require('../controllers/prizeController')
const ClassRecord = require('../controllers/classrecordController')
const Class = require('../controllers/ClassController')
const crypto = require('crypto')
const _ = require('lodash');
function routes(app) {
  app.get('/', function(req, res, next) {
    res.render('index', { title: '首页' })
  })
  //跨域用接口
  app.post('/get_info', async (req, res, next) => {
    // 管理员请求本院所有学生
    const whereObj = {}
    const managers = await Manager.findAll({ id: req.body.id }, [])
    let date = new Date()
    if (managers.length) {
      //如果是管理员，则是获取本院学生列表，查询条件不需要加入管理员id
      whereObj.department = managers[0].department
      date = req.body.date
    }else {
      // 如果是学生登录则是获取个人信息
      whereObj.id = req.body.id
    }
    const attributes = req.body.attributes || []
    const students = await Student.findAll(whereObj, attributes,date)
    res.json({ status: true, data: { students: students } })
  })

  app.post('/getSignupRecords', async (req, res, next) => {
    const { date, id } = req.body
    const whereObj = {}
    const managers = await Manager.findAll({ id }, [])
    if (!managers.length) {
      //如果是管理员，则是获取本院学生列表，查询条件不需要加入管理员id
      res.json({ status: false, data: { msg: '参数错误' } })
    }
    whereObj.department = managers[0].department
    const attributes = req.body.attributes || []
    const students = await Student.findAll(whereObj, attributes, date)
    res.json({ status: true, data: { students: students } })
  })
  app.get('/getClassRecords', async (req, res, next) => {
    const { date, id } = req.query
    const whereObj = {}
    const managers = await Manager.findAll({ id }, [])
    if (!managers.length) {
      //如果是管理员，则是获取本院学生列表，查询条件不需要加入管理员id
      res.json({ status: false, data: { msg: '参数错误' } })
    }
    whereObj.department = managers[0].department
    const attributes = req.body.attributes || []
    const classes = await Class.findAll(whereObj, attributes, date)
    res.json({ status: true, data: { classes } })
  })

  //跨域用接口
  app.post('/login', async (req, res, next) => {
    const { id, password } = req.body
    let permission = 'student'
    if (!id || !password) {
      res.json({ status: false, data: { msg: '缺少参数' } })
      return
    }
    const students = await Student.findAll({ id: id }, [])
    if (students.length) {
      const studentId = students[0].id
      if (password !== studentId.substr(studentId.length - 6, 6)) {
        res.json({ status: false, data: { msg: '密码错误' } })
        return
      }
      const permissions = ['班长', '团支书', '负责人']
      if (permissions.indexOf(students[0].permission) !== -1) {
        permission = 'monitor'
      }
      const hash = crypto
        .createHmac('sha256', students[0].id)
        .update(new Date().toString())
        .digest('hex')
      const result = await Student.update(id, { cookie: hash })
      if (result) {
        res.json({
          status: true,
          data: {
            _t_s_l_: hash,
            permission: permission,
            msg: '登陆成功',
            expire: new Date(Date.now() + 18000000).toString()
          }
        })
      } else {
        res.json({ status: false, data: { msg: '出现了一些错误' } })
      }
      return
    }
    //如果不是学号登录那就是工号了，去manage里面查询
    const managers = await Manager.findAll({ id: id }, [])
    if (password !== managers[0].password) {
      res.json({ status: false, data: { msg: '密码错误' } })
      return
    }
    permission = 'manage'
    const hash = crypto
      .createHmac('sha256', managers[0].id)
      .update(new Date().toString())
      .digest('hex')
    const result = await Manager.update(id, { cookie: hash })
    if (result) {
      res.json({
        status: true,
        data: {
          _t_s_l_: hash,
          msg: '登陆成功',
          manager: managers[0],
          permission: permission,
          expire: new Date(Date.now() + 18000000).toString()
        }
      })
    } else {
      res.render()
    }
  })

  //跨域用接口
  app.post('/get_students_class', async function(req, res, next) {
    const admin_cookie = req.body.cookie
    if (!admin_cookie) {
      res.send('请先登录')
      return
    }
    const monitor = await Student.findAll({ cookie: admin_cookie }, ['id', 'name', 'class'])
    if (!monitor.length) {
      res.send('登录已过期')
    }
    const students = await Student.findAll({ class: monitor[0].class }, ['id', 'name', 'class','status'])
    res.json({ status: true, data: { msg: '获取本班学生成功', students: students } })
  })
  //跨域用接口
  app.post('/update_status', async function(req, res, next) {
    const update_data = req.body
    const time = new Date()
    _.forEach(update_data, async (item)=>{
      const record = JSON.parse(item);
      await Student.update(record.id, {status: record.status})
      await SigninRecord.create({ studentId: record.id, status: record.status, time: time })
    })
    // for (let key in update_data) {
    //   await Student.update(key, JSON.parse(update_data[key]))
    //   // create_data.push({studentId:key,status:JSON.parse(update_data[key])['status'], time:new Date()})
    //   await SigninRecord.create({ studentId: key, status: JSON.parse(update_data[key])['status'], time: new Date() })
    // }
    const students = await Student.findAll({ id: JSON.parse(update_data[0]).id }, [])
    const curClass = students[0].class
    await ClassRecord.create({class:curClass,time:time})
    res.json({ status: true })
  })
  //跨域用接口
  app.post('/upsert_prize', (req, res, next) => {
    const upsert_data = JSON.parse(req.body.data)
    for (let i = 0; i < upsert_data.length; i++) {
      Prize.upsert(upsert_data[i])
    }
    // upsert_data.forEach(element => {
    //   await Prize.upsert(element);
    // });
    res.json({ status: true })
  })
  app.post('/delete_prize', (req, res, next)=>{
    const id = req.body.id;
    Prize.delete({id:id});
    res.json({
      status:true,
      message:'删除成功'
    })
  })

  //原前后端未分离接口
  app.post('/monitor_login', async function(req, res, next) {
    const request = req.body
    if (!request.id || !request.password) {
      res.send('登陆失败')
      return
    }
    const students = await Student.findAll({ id: request.id }, [])
    if (students[0].permission !== '班长') {
      res.send('你不是班级负责人，没有该权限')
      return
    }
    const idcard = students[0].idcard
    if (request.password !== idcard.substr(idcard.length - 6, 6)) {
      res.send('密码错误')
      return
    }
    const hash = crypto
      .createHmac('sha256', idcard)
      .update(new Date().toDateString())
      .digest('hex')
    const result = await Student.update(request.id, { cookie: hash })
    if (result) {
      res.cookie('_i_t_s_', hash, { expires: new Date(Date.now() + 1800000) })
      res.redirect('/class_sign_in')
    } else {
      res.render()
    }
  })
  app.get('/class_sign_in', async function(req, res, next) {
    const admin_cookie = req.cookies['_i_t_s_'] ? req.cookies['_i_t_s_'] : ''
    if (!admin_cookie) {
      res.send('请先登录')
      return
    }
    const monitor = await Student.findAll({ cookie: admin_cookie }, ['id', 'name', 'class'])
    if (!monitor.length) {
      res.send('登录已过期')
    }
    const students = await Student.findAll({ class: monitor[0].class }, ['id', 'name', 'status'])
    res.render('classSignin', {
      title: '班级签到',
      status: '登录成功',
      students: students
    })
  })
  app.get('/search', function(req, res, next) {
    res.render('search', { title: '学号查询' })
  })

  app.get('/monitor_login', function(req, res, next) {
    res.render('monitorLogin', { title: '班长登录' })
  })
  app.get('/manage', async (req, res, next) => {
    const cookie = req.cookies['_i_t_m_'] ? req.cookies['_i_t_m_'] : ''
    if (!cookie) {
      res.render('manage', { title: '学生信息管理', status: false, data: null, message: '请先登录' })
      return
    }
    const managers = await Manager.findAll({ cookie: cookie }, [])
    if (!managers.length) {
      res.send('请重新登录')
      return
    }
    const students = await Student.findAll({}, ['id', 'name', 'status'])
    res.render('manage', { title: '学生信息管理', status: true, students: students, message: null })
    //渲染界面
  })

  app.post('/manage', async (req, res, next) => {
    const { username, password } = req.body

    if (!username || !password) {
      res.send('登陆失败')
      return
    }
    const managers = await Manager.findAll({ username: username }, [])
    if (password !== managers[0].password) {
      res.send('密码错误')
      return
    }
    const hash = crypto
      .createHmac('sha256', password)
      .update(new Date().toDateString())
      .digest('hex')
    const result = await Manager.update(username, { cookie: hash })
    if (result) {
      res.cookie('_i_t_m_', hash, { expires: new Date(Date.now() + 1800000) })
      res.redirect('/manage')
    } else {
      res.render()
    }
  })
  app.get('/ask_for_leave', async (req, res, next) => {
    res.render('leave', { title: '在线请假' })
  })
}
module.exports = routes
